﻿/*
Configuration Server
 
Provides a single configuration point for the several instances (development, 
staging, testing, production, etc.) for web sites
 
Includes ideas and code from all over the internet. Specially, stacktrace, msdn, github.
 
Copyright (C) 2014 by Jaime Espinosa <jaimeespinosa60@gmail.com>
 
The MIT License (MIT)

Copyright (c) 2014 jaime espinosa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

  @author Jaime Espinosa <jaimeespinosa60@gmail.com>
  @package configuracion
  @version 0.1
*/

using Configuracion.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;

namespace Configuracion.Controllers
{
    public class ownerController : baseController
    {
        [Authorize]
        public ActionResult list()
        {
            ViewBag.Exception = "";
            IQueryable<mdlOwner> owner = default(IQueryable<mdlOwner>);

            string strUserName = User.Identity.Name;
            owner = from p in dbContext.Owners
                    where p.users.Any(b => b.userName == strUserName)
                    select p;


            return View(owner);
        }
        [Authorize]
        public JsonResult newOwner(string strName = "", string strDescription = "")
        {
            string strError = "";
            mdlOwner newOwner = default(mdlOwner);

            if ((strName == "") || (strDescription == ""))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                newOwner = new mdlOwner();
                newOwner.name = strName;
                newOwner.description = strDescription;
                newOwner.users = new List<mdlUser>() { new mdlUser(User.Identity.Name) };

                dbContext.Owners.Add(newOwner);

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    throw new Exception("Please verify:" + strError.ToString());
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "owner created" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult editOwner(int ownerKey = 0, string strName = "", string strDescription = "")
        {
            string strError = "";
            mdlOwner editOwner = default(mdlOwner);

            if ((ownerKey == 0) || (strName == "") || (strDescription == ""))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                string strUserName = User.Identity.Name;
                editOwner = (from p in dbContext.Owners
                             where p.users.Any(b => b.userName == strUserName)
                             & p.ID == ownerKey
                             select p).FirstOrDefault<mdlOwner>();

                if (editOwner == null)
                    return Json(new { error = "owner not found" }, JsonRequestBehavior.AllowGet);

                // UPDATES owner
                editOwner.name = strName;
                editOwner.description = strDescription;

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    throw new Exception("Please verify:" + strError.ToString());
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "owner updated" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult dropOwner(int ownerKey = 0)
        {
            string strError = "";
            mdlOwner removeOwner = default(mdlOwner);

            if (ownerKey == 0)
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                string strUserName = User.Identity.Name;
                removeOwner = (from p in dbContext.Owners.Include(P => P.users)
                               where p.users.Any(b => b.userName == strUserName)
                               & p.ID == ownerKey
                               select p).FirstOrDefault<mdlOwner>();

                if (removeOwner == null)
                    return Json(new { error = "owner not found" }, JsonRequestBehavior.AllowGet);

                // REMOVES USERS
                if (removeOwner.users.Count > 1)
                    throw new Exception("Owner has users. Please delete all users (except self) before deleting owner:" + strError.ToString());

                // DELETES SELF
                if ((removeOwner.users.Count == 1) && (removeOwner.users.First<mdlUser>().userName == User.Identity.Name))
                {
                    dbContext.Users.Remove(removeOwner.users.First<mdlUser>());
                }

                // REMOVE THE OWNER
                dbContext.Owners.Remove(removeOwner);

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    throw new Exception("Please verify:" + strError.ToString());
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "owner removed" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult infoowner(int ownerKey = 0)
        {

            mdlOwner infoOwner = default(mdlOwner);

            if (ownerKey == 0)
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                string strUserName = User.Identity.Name;
                infoOwner = (from p in dbContext.Owners
                             where p.users.Any(b => b.userName == strUserName)
                             & p.ID == ownerKey
                             select p).FirstOrDefault<mdlOwner>();

                if (infoOwner == null)
                    return Json(new { error = "owner not found" }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { OK = "owner obtained", data = infoOwner }, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        public JsonResult ownerList()
        {
            IQueryable<mdlOwner> owners = default(IQueryable<mdlOwner>);

            try
            {
                string strUserName = User.Identity.Name;
                owners = (from p in dbContext.Owners
                          where p.users.Any(b => b.userName == strUserName)
                          select p);

                if (owners == null)
                    return Json(new { error = "owners not found" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { OK = "List obtained", data = owners }, JsonRequestBehavior.AllowGet);
        }
    }
}